package com.bins.dentist.clinic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bins.dentist.clinic.mapper.RolePermissionMapper;
import com.bins.dentist.clinic.model.dto.RolePermDto;
import com.bins.dentist.clinic.entity.RolePermissionEntity;
import com.bins.dentist.clinic.service.RolePermissionService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bins
 * @since 2023-02-20 20:53:31
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermissionEntity> implements RolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Long> getIdsByRoleId(Long roleId) {
        LambdaQueryWrapper<RolePermissionEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(RolePermissionEntity::getRoleId, roleId);
        List<RolePermissionEntity> rolePermList = rolePermissionMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(rolePermList)) {
            return Collections.emptyList();
        }
        return rolePermList.stream().map(RolePermissionEntity::getPermissionId).collect(Collectors.toList());
    }

    @Override
    public int deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<RolePermissionEntity> deleteWrapper = new LambdaQueryWrapper();
        deleteWrapper.eq(RolePermissionEntity::getRoleId, roleId);
        return rolePermissionMapper.delete(deleteWrapper);
    }

    @Override
    public List<RolePermissionEntity> buildRolePermList(RolePermDto dto) {
        List<RolePermissionEntity> perms = Lists.newArrayListWithCapacity(dto.getPermIds().size());
        RolePermissionEntity rolePerm;
        for (Long permId : dto.getPermIds()) {
            rolePerm = new RolePermissionEntity();
            rolePerm.setRoleId(dto.getRoleId());
            rolePerm.setPermissionId(permId);
            perms.add(rolePerm);
        }
        return perms;
    }
}
